import {
  removeOrderFormProduct,
  resetForm,
  updateOrderForm,
  updateOrderFormProduct,
} from '../reducers/order-form';
import HttpClient from '../commons/http-client';
import {PageOederProductParams, ProductType} from '../reducers/constant';
import {formatDate} from '../utils';
import {NavigationActions, StackActions} from 'react-navigation';
import _ from 'lodash';
import Toast from '../components/toast';
import {I18n} from '../reducers/intl';
import {loadOrders} from './order-actions';

export function updateForm(payload) {
  return dispatch => {
    dispatch(updateOrderForm(payload));
  };
}

export function updateProduct(payload) {
  return dispatch => {
    dispatch(updateOrderFormProduct(payload));
  };
}

export function removeProduct(payload) {
  return dispatch => {
    dispatch(removeOrderFormProduct(payload));
  };
}

export function submit() {
  return async (dispatch, getState) => {
    const {orderForm, user} = getState();
    if (!user.approved) {
      return Toast.show(I18n.t('toast.noAuth'), {width: 240});
    }
    const payload = {
      order: {
        buyer: orderForm.buyer.id,
        seller: orderForm.seller.id,
        patient_name: orderForm.patientName,
        patient_gender: orderForm.patientGender,
        patient_age: orderForm.patientAge,
        delivery_day: formatDate(orderForm.deliveryDay),
        selections: _.get(orderForm, 'selections', []).map(v => v.id),
        remark: orderForm.note,
        items: [],
        images: Object.values(orderForm.files || {}).map(f => f.id),
      },
      items: Object.values(orderForm.products || {}).map(p => {
        const productItem = {};
        Object.keys(p).forEach(pk => {
          const params =
            p.product.type === ProductType.fixed
              ? PageOederProductParams.fixed
              : PageOederProductParams.remvArch;
          if (Object.keys(params).includes(pk)) {
            productItem[params[pk]] = p[pk].id;
          }
        });
        if (p.product.type === ProductType.fixed) {
          productItem.fixed_product = p.product.id;
        } else {
          productItem.remv_arch = p.product.id;
        }
        if (p.others) {
          productItem.others = p.others.map(v => v.id);
        }
        return {
          type: p.product.type,
          redo: p.redo,
          ...productItem,
          tooth_link: p.gum && p.gum.join(','),
          link_str: p.join && p.join.join(','),
        };
      }),
    };
    try {
      await HttpClient.post('/web/dent/order/new', payload);
      dispatch(reset());
      dispatch(loadOrders({}, 1));
      dispatch(StackActions.popToTop());
      // await dispatch(NavigationActions.navigate({routeName: 'Main'}));
      await dispatch(NavigationActions.navigate({routeName: 'OrderList'}));
    } catch (e) {
      if (e.message === 'Request failed with status code 403') {
        return Toast.show(I18n.t('toast.noAuth'), {width: 240});
      }
      Toast.show(e.message);
    }
  };
}

export function reset() {
  return dispatch => {
    dispatch(resetForm());
  };
}
